﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Configuration;
using System.IO;
using ProcessControl.Logic;
using ProcessControl.Entity;
using MyLib;
using Portal.Interface;

namespace ProcessControl
{
    public partial class Attachments_TY : System.Web.UI.UserControl
    {

        /// <summary>
        /// 是否可以上传
        /// </summary>
        // private bool ReadOnly;
        public bool ReadOnly
        {
            get { return uploadrow.Visible; }
            set
            {
                uploadrow.Visible = !value;
                if (value)
                {
                    txtReadonly.Text = "1";
                }
                else
                {
                    txtReadonly.Text = "0";
                }
            }
        }

        public bool Required
        {
            get
            {
                if (this.txtMust.Text == "1")
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            set
            {
                if (value)
                {
                    txtMust.Text = "1";
                }
                else
                {
                    txtMust.Text = "0";
                }
            }
        }

        private AttachmentLogic logic = new AttachmentLogic();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                try
                {
                    string type = Request.QueryString["Type"];
                    if (!string.IsNullOrEmpty(type))
                    {
                        if (type.ToUpper() == "MYAPPROVAL" || type.ToUpper() == "MYREQUEST") //已完成，不显示上传按钮
                        {
                            this.actionRow.Visible = false;
                            this.uploadrow.Visible = false;
                        }
                    }
                    BindAttachments();
                    this.actionRow.Visible = ReadOnly;
                }
                catch (System.Exception ex)
                {
                    MyLib.LogUtil.Error(ex);
                    this.Page.ClientScript.RegisterStartupScript(this.Page.GetType(), "message", "<script language='javascript' defer>alert('" + ex.Message.Replace("\n", " ").Replace("<br/>", " ").Replace("'", "") + "');</script>");
                }
            }
        }


        void BindAttachments()
        {
            try
            {
                UserInfo_TY userInfo = Page.FindControl("UserInfo1") as UserInfo_TY;
                string processName = userInfo.ProcessName;
                int incident = ConvertUtil.ToInt32(userInfo.Incident);
                Repeater1.DataSource = logic.GetAttachmentsByFormID(userInfo.FormId);
                Repeater1.DataBind();
            }
            catch (System.Exception ex)
            {
                MyLib.LogUtil.Error(ex);
                this.Page.ClientScript.RegisterStartupScript(this.Page.GetType(), "message", "<script language='javascript' defer>alert('" + ex.Message.Replace("\n", " ").Replace("<br/>", " ").Replace("'", "") + "');</script>");
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            try
            {
                UserInfo_TY userInfo = Page.FindControl("UserInfo1") as UserInfo_TY;
                string processName = userInfo.ProcessName;
                int incident = ConvertUtil.ToInt32(userInfo.Incident);
                string stepName = userInfo.StepName;
                AttachmentEntity item = new AttachmentEntity();
                item.ProcessName = processName;
                item.Incident = incident;
                item.UploadStepName = stepName;
                item.FileName = FilePath.FileName;
                item.NewName = Guid.NewGuid().ToString();
                item.FileType = item.FileName.Substring(item.FileName.LastIndexOf("."), item.FileName.Length - item.FileName.LastIndexOf("."));
                item.FileSize = FilePath.FileContent.Length;
                item.Status = "正常";
                item.CreateByBadge = Page.User.Identity.Name;
                try
                {
                    IOrg _org = ServiceContainer.Instance().GetService<IOrg>();
                    Portal.Entity.UserEntity ue = _org.GetUserEntity(Page.User.Identity.Name);
                    item.CreateByName = string.IsNullOrEmpty(ue.CNName) ? userInfo.Applicant : ue.CNName;
                }
                catch (Exception ex)
                {
                    LogUtil.Info("Get Attachment uploader error:" + ex.Message);
                    item.CreateByName = userInfo.Applicant;
                }

                item.Comments = FileComments.Text;
                item.CreateDate = DateTime.Now;
                item.Ext01 = userInfo.FormId; //表单唯一号
                item.Ext02 = "";
                item.Ext03 = "";
                item.Ext04 = "";
                item.Ext05 = "";

                string path = Server.MapPath(MyLib.ConfigurationManager.AppSettings["AttachmentPath"]) + "/" + processName + "/";
                //string path = MyLib.ConfigurationManager.AppSettings["AttachmentPath"] + "/";
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);

                }
                //System.Net.WebClient webClient = new System.Net.WebClient();
                // webClient.UploadFile(path, FilePath.FileName);
                FilePath.SaveAs(path + item.NewName + item.FileType);

                if (logic.UploadFile(item))
                {
                    BindAttachments();
                }
                else
                {
                    File.Delete(path);
                    //MessageBox.Show(Page, "File Upload Error.");
                }
                FileComments.Text = "";
            }
            catch (Exception ex)
            {
                MyLib.LogUtil.Error(ex);
                this.Page.ClientScript.RegisterStartupScript(this.Page.GetType(), "message", "<script language='javascript' defer>alert('" + ex.Message.Replace("\n", " ").Replace("<br/>", " ").Replace("'", "") + "');</script>");
            }
        }

        protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            try
            {
                if (e.CommandName == "Download")
                {
                    try
                    {
                        logic.DownloadByID(this.Page, e.CommandArgument.ToString());
                    }
                    catch (Exception ex)
                    {
                        //MessageBox.Show(Page, ex.Message);
                    }
                }
                if (e.CommandName == "Delete")
                {
                    try
                    {
                        if (logic.DeleteAttachmentsByID(e.CommandArgument.ToString()))
                        {
                            BindAttachments();
                        }
                        else
                        {
                            throw new Exception("Delete Attachments Error.");
                        }
                    }
                    catch (Exception ex)
                    {
                        //MessageBox.Show(Page, ex.Message);
                    }
                }
            }
            catch (System.Exception ex)
            {
                MyLib.LogUtil.Error(ex);
                this.Page.ClientScript.RegisterStartupScript(this.Page.GetType(), "message", "<script language='javascript' defer>alert('" + ex.Message.Replace("\n", " ").Replace("<br/>", " ").Replace("'", "") + "');</script>");
            }
        }
    }
}